<template>
  <div
    ref="custom-table"
    class="custom-table-container"
    :class="{ 'vab-fullscreen': isFullscreen }"
  >
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form
          ref="form"
          :inline="true"
          label-width="80px"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item
            label="设备名称"
            label-width="70px"
            prop="condition.deviceName"
          >
            <el-input
              v-model="queryForm.condition.deviceName"
              clearable
              placeholder="请输入设备名称"
            />
          </el-form-item>
          <el-form-item label="设备编码" prop="condition.deviceNo">
            <el-input
              v-model="queryForm.condition.deviceNo"
              clearable
              placeholder="请输入设备编码"
            />
          </el-form-item>
          <el-form-item
            v-show="!fold"
            label="设备类型"
            prop="condition.deviceType"
          >
            <el-select
              v-model="queryForm.condition.deviceType"
              clearable
              placeholder="请选择设备类型"
            >
              <el-option
                v-for="item in deviceType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-show="!fold" label="小区编码" prop="condition.areaNo">
            <el-select
              v-model="queryForm.condition.areaNo"
              clearable
              placeholder="请选择小区编码"
            >
              <el-option
                v-for="item in cellCode"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              native-type="submit"
              type="primary"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button icon="el-icon-refresh-left" @click="resetQuery">
              重置
            </el-button>
            <el-button type="text" @click="handleFold">
              <span v-if="fold">展开</span>
              <span v-else>合并</span>
              <vab-icon
                class="vab-dropdown"
                :class="{ 'vab-dropdown-active': fold }"
                icon="arrow-up-s-line"
              />
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :lg="8" :md="8" :sm="12" :xl="8" :xs="12">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          添加设备
        </el-button>
        <el-button
          v-permissions="['SUPER']"
          icon="el-icon-download"
          :loading="isExporting"
          @click="exportEqList"
        >
          导出设备
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :lg="16" :md="16" :sm="12" :xl="16" :xs="12">
        <el-button
          style="margin: 0 10px 10px 0 !important"
          type="primary"
          @click="clickFullScreen"
        >
          <vab-icon
            :icon="isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'"
          />
          表格全屏
        </el-button>
        <el-popover
          ref="popover"
          popper-class="custom-table-checkbox"
          trigger="hover"
        >
          <el-radio-group v-model="lineHeight">
            <el-radio label="medium">大</el-radio>
            <el-radio label="small">中</el-radio>
            <el-radio label="mini">小</el-radio>
          </el-radio-group>
          <template #reference>
            <el-button style="margin: 0 10px 10px 0 !important" type="primary">
              <vab-icon icon="line-height" />
              表格尺寸
            </el-button>
          </template>
        </el-popover>
        <el-popover popper-class="custom-table-checkbox" trigger="hover">
          <el-checkbox-group v-model="checkList">
            <vab-draggable v-bind="dragOptions" :list="columns">
              <div v-for="(item, index) in columns" :key="item + index">
                <vab-icon icon="drag-drop-line" />
                <el-checkbox
                  :disabled="item.disableCheck === true"
                  :label="item.label"
                >
                  {{ item.label }}
                </el-checkbox>
              </div>
            </vab-draggable>
          </el-checkbox-group>
          <template #reference>
            <el-button
              icon="el-icon-setting"
              style="margin: 0 0 10px 0 !important"
              type="primary"
            >
              可拖拽列设置
            </el-button>
          </template>
        </el-popover>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :border="border"
      :data="list"
      :size="lineHeight"
      :stripe="stripe"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        label="序号"
        show-overflow-tooltip
        width="95"
      >
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        :width="item.width"
      >
        <template #default="{ row }">
          <template v-if="item.label.indexOf('照片') > -1">
            <el-image
              :preview-src-list="imageList"
              :src="baseUrl + row[item.prop]"
            />
          </template>
          <template v-else-if="item.label === '设备控制'">
            <el-switch
              v-model="row[item.prop]"
              :active-value="1"
              :inactive-value="0"
              @change="(v) => changeDevice(row, v)"
            />
          </template>
          <template v-else-if="item.label === '设备类型'">
            <span>saihe</span>
          </template>
          <template v-else-if="item.label === '设备状态'">
            <span v-if="row[item.prop] === 1 && row['sdkStatus'] === 1">
              <el-tooltip :content="deviceMap[row[item.prop]]">
                <span>
                  <span class="vab-dot vab-dot-success">
                    <span></span>
                  </span>
                  <span>{{ deviceMap[row[item.prop]] }}</span>
                </span>
              </el-tooltip>
            </span>
            <span v-else>
              <el-tooltip :content="deviceMap[row[item.prop]]">
                <span>
                  <span class="vab-dot vab-dot-error">
                    <span></span>
                  </span>
                  <span>{{ deviceMap[row[item.prop]] }}</span>
                </span>
              </el-tooltip>
            </span>
          </template>
          <span v-else>{{ row[item.prop] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="100">
        <template #default="{ row }">
          <el-dropdown>
            <span class="el-dropdown-link">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-video-camera">
                <el-button type="text" @click="previewUrl(row)">
                  视频预览
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-s-platform">
                <el-button type="text" @click="watchUrl(row)">
                  视频回放
                </el-button>
              </el-dropdown-item>
              <template v-if="true" v-permissions="['SUPER']">
                <el-dropdown-item
                  v-if="row.sdkStatus === 0"
                  icon="el-icon-circle-check"
                >
                  <el-button type="text" @click="startTheDevice(row)">
                    启动服务
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="row.sdkStatus === 1"
                  icon="el-icon-circle-close"
                >
                  <el-button type="text" @click="stopTheDevice(row)">
                    停止服务
                  </el-button>
                </el-dropdown-item>
              </template>
              <el-dropdown-item v-permissions="['SUPER']" icon="el-icon-edit">
                <el-button type="text" @click="handleEdit(row)">修改</el-button>
              </el-dropdown-item>
              <el-dropdown-item v-permissions="['SUPER']" icon="el-icon-delete">
                <el-button type="text" @click="handleDelete(row)">
                  删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <template #empty>
        <el-image
          class="vab-data-empty"
          :src="require('@/assets/empty_images/data_empty.png')"
        />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <device-edit ref="edit" @fetch-data="fetchData" />
    <live-video ref="videoRef" />
    <history-video ref="hlsRef" />
    <iframe ref="down_load_frame" style="display: none"></iframe>
  </div>
</template>

<script>
  import {
    getEquipments,
    updateDeviceState,
    deleteDeviceById,
    exportDevice,
    startDevice,
    stopDevice,
  } from '@/api/record'
  import DeviceEdit from '../components/DeviceEdit'
  import LiveVideo from './components/LiveVideo'
  import { picBaseUrl } from '@/config'
  import VabDraggable from 'vuedraggable'
  import { mapGetters } from 'vuex'
  import HistoryVideo from '@/views/business/equipmentManagement/components/HistoryVideo'

  const deviceStatus = {
    0: '未启动',
    1: '运行中',
    2: '断线中',
    3: '进程停止',
  }
  export default {
    name: 'EquipmentManagement',
    components: {
      HistoryVideo,
      DeviceEdit,
      VabDraggable,
      LiveVideo,
    },
    data() {
      return {
        deviceMap: deviceStatus,
        baseUrl: picBaseUrl,
        isFullscreen: false,
        border: true,
        fold: true,
        height: this.$baseTableHeight(1),
        stripe: false,
        lineHeight: 'medium',
        checkList: [
          '设备名称',
          '设备状态',
          '设备控制',
          '设备编码',
          'IP地址',
          '设备安装地址',
          '设备类型',
          '经度',
          '纬度',
          '小区编码',
          '摄像头Code',
          '预览地址',
        ],
        columns: [
          {
            label: '设备名称',
            width: '150',
            prop: 'deviceName',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '设备状态',
            width: '150',
            prop: 'status',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '设备控制',
            width: '120',
            prop: 'enable',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '设备编码',
            width: '150',
            prop: 'deviceNo',
            sortable: false,
          },
          {
            label: 'IP地址',
            width: '150',
            prop: 'ip',
            sortable: false,
          },
          {
            label: '设备安装地址',
            width: '200',
            prop: 'installAddress',
            sortable: false,
          },
          {
            label: '设备类型',
            width: '100',
            prop: 'deviceManufacturer',
            sortable: false,
          },
          {
            label: '经度',
            width: '100',
            prop: 'longitude',
            sortable: false,
          },
          {
            label: '纬度',
            width: '100',
            prop: 'latitude',
            sortable: false,
          },
          {
            label: '小区编码',
            width: '200',
            prop: 'areaName',
            sortable: false,
          },
          {
            label: '摄像头Code',
            width: '100',
            prop: 'cameraCode',
            sortable: false,
          },
          {
            label: '预览地址',
            width: '200',
            prop: 'previewUrl',
            sortable: false,
          },
        ],
        list: [],
        imageList: [],
        listLoading: true,
        isExporting: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          condition: {
            orderBy: 'id',
            orderDirect: 'desc',
            deviceName: '',
            deviceNo: '',
            areaNo: '',
            deviceType: '',
          },
          pageNum: 1,
          pageSize: 10,
          title: '',
        },
      }
    },
    computed: {
      ...mapGetters({
        cellCode: 'dict/cellCode',
        deviceType: 'dict/deviceType',
      }),
      dragOptions() {
        return {
          animation: 600,
          group: 'description',
        }
      },
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      exportEqList() {
        this.isExporting = true
        exportDevice()
          .then((res) => {
            if (res && res.status === 0) {
              this.$baseMessage(
                '数据导出成功！',
                'success',
                'vab-hey-message-success'
              )
              this.$refs['down_load_frame'].src = this.baseUrl + res.data
              setTimeout(() => {
                this.$refs['down_load_frame'].src = ''
              }, 100)
            } else {
              this.$baseMessage(
                res ? res.msg : '数据导出失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            this.$baseMessage(
              '导出失败，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
          .then(() => {
            this.isExporting = false
          })
      },
      changeDevice(row, y) {
        let initState = 0
        if (y === 1) {
          initState = 0
        } else {
          initState = 0
        }
        updateDeviceState(row.id, y)
          .then((res) => {
            if (res && res.status === 0) {
              this.$baseMessage(
                '状态修改成功！',
                'success',
                'vab-hey-message-success'
              )
            } else {
              row['enable'] = initState
              this.$baseMessage(
                res ? res.msg : '状态修改失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            row['enable'] = initState
            this.$baseMessage(
              '修改失败，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
      },
      startTheDevice(row) {
        console.log(row)
        const loadingInstance = this.$loading({
          lock: true,
          text: '设备启动中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        startDevice(row.id)
          .then((res) => {
            loadingInstance.close()
            if (res && res.status === 0) {
              this.$baseMessage(
                '设备启动成功！',
                'success',
                'vab-hey-message-success'
              )
              this.fetchData()
            } else {
              this.$baseMessage(
                res ? res.msg : '设备启动失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            loadingInstance.close()
            this.$baseMessage(
              '操作失败，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
      },
      stopTheDevice(row) {
        console.log(row)
        const loadingInstance = this.$loading({
          lock: true,
          text: '设备停止中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        stopDevice(row.id)
          .then((res) => {
            loadingInstance.close()
            if (res && res.status === 0) {
              this.$baseMessage(
                '设备停止成功！',
                'success',
                'vab-hey-message-success'
              )
              this.fetchData()
            } else {
              this.$baseMessage(
                res ? res.msg : '设备停止失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            loadingInstance.close()
            this.$baseMessage(
              '操作失败，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
      },
      clickFullScreen() {
        this.isFullscreen = !this.isFullscreen
        this.handleHeight()
      },
      handleFold() {
        this.fold = !this.fold
        this.handleHeight()
      },
      handleHeight() {
        if (this.isFullscreen) this.height = this.$baseTableHeight(1) + 210
        else this.height = this.$baseTableHeight(1)
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      previewUrl(row) {
        console.log(row)
        this.$refs['videoRef'].showEdit(row)
      },
      watchUrl(row) {
        console.log(row)
        this.$refs['hlsRef'].showEdit(row)
      },
      handleEdit(row) {
        if (row && row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        console.log(row)
        this.$baseConfirm('确定要删除当前项吗', null, async () => {
          try {
            const res = await deleteDeviceById(row.id)
            if (res && res.status === 0) {
              this.$baseMessage(
                '删除成功！',
                'success',
                'vab-hey-message-success'
              )
              await this.fetchData()
            } else {
              this.$baseMessage(
                res ? res.msg : '删除失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          } catch (e) {
            console.log(e)
            this.$baseMessage(
              e ? e.message : '删除失败！',
              'error',
              'vab-hey-message-error'
            )
          }
        })
      },
      async fetchData() {
        this.listLoading = true
        try {
          const res = await getEquipments(this.queryForm)
          if (res && res.data) {
            const { list, total } = res.data
            this.list = list || []
            const imageList = []
            list.forEach((item) => {
              item.faceImagePath &&
                imageList.push(this.baseUrl + item.faceImagePath)
              item.backImagePath &&
                imageList.push(this.baseUrl + item.backImagePath)
            })
            this.imageList = imageList
            this.total = total
          }
        } catch (e) {
          console.log(e)
        }
        this.listLoading = false
      },
      resetQuery() {
        this.$refs['form'].resetFields()
        this.queryForm.pageNum = 1
        this.fetchData()
      },
    },
  }
</script>

<style lang="scss" scoped>
  .custom-table-container {
    ::v-deep {
      i {
        cursor: pointer;
      }
    }

    .stripe-panel,
    .border-panel {
      margin: 0 10px $base-margin/2 10px !important;
    }
  }
</style>
<style lang="scss">
  .custom-table-checkbox {
    [class*='ri'] {
      vertical-align: -2.5px;
      cursor: pointer;
    }

    .el-checkbox {
      margin: 5px 0 5px 8px;
    }
  }
</style>
